<template>
    <view class="container">
      <app-header title="报名管理" />
      
      <view class="filter-container">
        <view class="search-box">
          <input 
            class="search-input" 
            type="text" 
            v-model="searchKeyword" 
            placeholder="搜索学员姓名/手机号" 
            @input="handleSearch"
          />
          <text class="search-icon">🔍</text>
        </view>
        
        <view class="filter-options">
          <picker 
            mode="selector" 
            :range="statusOptions" 
            range-key="label" 
            :value="statusIndex" 
            @change="handleStatusChange"
          >
            <view class="filter-item">
              <text>状态：</text>
              <text>{{ statusOptions[statusIndex].label }}</text>
            </view>
          </picker>
          
          <picker 
            mode="selector" 
            :range="licenseTypeOptions" 
            range-key="label" 
            :value="licenseTypeIndex" 
            @change="handleLicenseTypeChange"
          >
            <view class="filter-item">
              <text>驾照类型：</text>
              <text>{{ licenseTypeOptions[licenseTypeIndex].label }}</text>
            </view>
          </picker>
        </view>
      </view>
      
      <view v-if="loading" class="loading-container">
        <loading-state />
      </view>
      
      <view v-else-if="enrollments.length === 0" class="empty-container">
        <empty-state text="暂无报名申请" />
      </view>
      
      <view v-else class="enrollment-list">
        <view 
          class="enrollment-item card" 
          v-for="(item, index) in enrollments" 
          :key="index"
          @click="viewEnrollmentDetail(item)"
        >
          <view class="enrollment-header">
            <view class="enrollment-name">{{ item.user.real_name }}</view>
            <status-badge :status="item.status" type="enrollment" />
          </view>
          
          <view class="enrollment-info">
            <view class="info-item">
              <text class="info-label">驾照类型：</text>
              <text class="info-value">{{ getLicenseTypeText(item.license_type) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">手机号码：</text>
              <text class="info-value">{{ item.user.phone }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">报名时间：</text>
              <text class="info-value">{{ formatDate(item.created_at) }}</text>
            </view>
          </view>
          
          <view class="enrollment-actions">
            <button 
              class="btn-action btn-view" 
              @click.stop="viewEnrollmentDetail(item)"
            >
              查看
            </button>
            <button 
              class="btn-action btn-approve" 
              v-if="item.status === 'reviewing'"
              @click.stop="approveEnrollment(item)"
            >
              通过
            </button>
            <button 
              class="btn-action btn-reject" 
              v-if="item.status === 'reviewing'"
              @click.stop="rejectEnrollment(item)"
            >
              拒绝
            </button>
          </view>
        </view>
      </view>
      
      <!-- 分页 -->
      <view class="pagination" v-if="enrollments.length > 0">
        <button 
          class="btn-page" 
          :disabled="page <= 1"
          @click="prevPage"
        >
          上一页
        </button>
        <text class="page-info">{{ page }}/{{ totalPages }}</text>
        <button 
          class="btn-page" 
          :disabled="page >= totalPages"
          @click="nextPage"
        >
          下一页
        </button>
      </view>
    </view>
  </template>
  
  <script>
  import { mapGetters } from 'vuex';
  import { formatDate } from '@/utils/date';
  import config from '@/config/index';
  import AppHeader from '@/components/common/AppHeader';
  import LoadingState from '@/components/common/LoadingState';
  import EmptyState from '@/components/common/EmptyState';
  import StatusBadge from '@/components/business/StatusBadge';
  
  export default {
    components: {
      AppHeader,
      LoadingState,
      EmptyState,
      StatusBadge
    },
    data() {
      return {
        enrollments: [],
        total: 0,
        page: 1,
        pageSize: 10,
        loading: true,
        searchKeyword: '',
        statusOptions: [
          { value: '', label: '全部状态' },
          { value: 'pending', label: '待提交材料' },
          { value: 'reviewing', label: '审核中' },
          { value: 'approved', label: '已通过' },
          { value: 'rejected', label: '已拒绝' }
        ],
        statusIndex: 0,
        licenseTypeOptions: [
          { value: '', label: '全部类型' },
          ...config.licenseTypes
        ],
        licenseTypeIndex: 0
      };
    },
    computed: {
      ...mapGetters('user', [
        'isAdmin'
      ]),
      totalPages() {
        return Math.ceil(this.total / this.pageSize);
      }
    },
    onLoad() {
      if (this.isAdmin) {
        this.loadEnrollments();
      } else {
        this.showToast('您没有管理员权限');
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },
    methods: {
      formatDate,
      getLicenseTypeText(type) {
        const license = config.licenseTypes.find(item => item.value === type);
        return license ? license.label : type;
      },
      loadEnrollments() {
        this.loading = true;
        
        // 准备查询参数
        const params = {
          page: this.page,
          pageSize: this.pageSize
        };
        
        // 添加筛选条件
        if (this.searchKeyword) {
          params.search = this.searchKeyword;
        }
        
        if (this.statusOptions[this.statusIndex].value) {
          params.status = this.statusOptions[this.statusIndex].value;
        }
        
        if (this.licenseTypeOptions[this.licenseTypeIndex].value) {
          params.license_type = this.licenseTypeOptions[this.licenseTypeIndex].value;
        }
        
        // 这里简化处理，实际项目中应该从API获取数据
        setTimeout(() => {
          // 模拟数据
          const mockData = {
            list: [
              {
                id: 1,
                user_id: 1,
                license_type: 'C1',
                status: 'reviewing',
                coach_id: null,
                created_at: '2025-04-01 10:00:00',
                updated_at: '2025-04-01 10:00:00',
                user: {
                  id: 1,
                  real_name: '张三',
                  phone: '13800138001'
                }
              },
              {
                id: 2,
                user_id: 2,
                license_type: 'C2',
                status: 'pending',
                coach_id: null,
                created_at: '2025-04-02 11:00:00',
                updated_at: '2025-04-02 11:00:00',
                user: {
                  id: 2,
                  real_name: '李四',
                  phone: '13800138002'
                }
              },
              {
                id: 3,
                user_id: 3,
                license_type: 'B2',
                status: 'approved',
                coach_id: 1,
                created_at: '2025-04-03 12:00:00',
                updated_at: '2025-04-03 12:00:00',
                user: {
                  id: 3,
                  real_name: '王五',
                  phone: '13800138003'
                }
              }
            ],
            total: 3,
            page: 1,
            pageSize: 10
          };
          
          this.enrollments = mockData.list;
          this.total = mockData.total;
          this.loading = false;
        }, 1000);
      },
      handleSearch() {
        this.page = 1;
        this.loadEnrollments();
      },
      handleStatusChange(e) {
        this.statusIndex = e.detail.value;
        this.page = 1;
        this.loadEnrollments();
      },
      handleLicenseTypeChange(e) {
        this.licenseTypeIndex = e.detail.value;
        this.page = 1;
        this.loadEnrollments();
      },
      prevPage() {
        if (this.page > 1) {
          this.page--;
          this.loadEnrollments();
        }
      },
      nextPage() {
        if (this.page < this.totalPages) {
          this.page++;
          this.loadEnrollments();
        }
      },
      viewEnrollmentDetail(enrollment) {
        uni.navigateTo({
          url: `/pages/admin/enrollment-detail?id=${enrollment.id}`
        });
      },
      approveEnrollment(enrollment) {
        this.showModal(`确认通过 ${enrollment.user.real_name} 的报名申请吗？`)
          .then(confirm => {
            if (confirm) {
              uni.showLoading({
                title: '处理中...'
              });
              
              // 这里简化处理，实际项目中应该调用API
              setTimeout(() => {
                uni.hideLoading();
                this.showToast('审核通过成功', 'success');
                // 重新加载数据
                this.loadEnrollments();
              }, 1000);
            }
          });
      },
      rejectEnrollment(enrollment) {
        uni.showModal({
          title: '拒绝申请',
          content: '确认拒绝申请？请输入拒绝原因',
          editable: true,
          placeholderText: '请输入拒绝原因',
          success: res => {
            if (res.confirm) {
              const remark = res.content;
              
              if (!remark) {
                this.showToast('请输入拒绝原因');
                return;
              }
              
              uni.showLoading({
                title: '处理中...'
              });
              
              // 这里简化处理，实际项目中应该调用API
              setTimeout(() => {
                uni.hideLoading();
                this.showToast('申请已拒绝', 'success');
                // 重新加载数据
                this.loadEnrollments();
              }, 1000);
            }
          }
        });
      }
    }
  };
  </script>
  
  <style lang="scss">
  .container {
    padding: 30rpx;
  }
  
  .filter-container {
    margin-bottom: 30rpx;
  }
  
  .search-box {
    position: relative;
    margin-bottom: 20rpx;
  }
  
  .search-input {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    padding: 0 80rpx 0 20rpx;
    font-size: 28rpx;
    color: #333;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    box-sizing: border-box;
  }
  
  .search-icon {
    position: absolute;
    right: 20rpx;
    top: 20rpx;
    font-size: 40rpx;
    color: #999;
  }
  
  .filter-options {
    display: flex;
    justify-content: space-between;
  }
  
  .filter-item {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    padding: 20rpx 0;
  }
  
  .loading-container, .empty-container {
    padding: 60rpx 0;
  }
  
  .enrollment-list {
    margin-bottom: 40rpx;
  }
  
  .enrollment-item {
    padding: 30rpx;
    margin-bottom: 20rpx;
  }
  
  .enrollment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
  }
  
  .enrollment-name {
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .enrollment-info {
    margin-bottom: 20rpx;
  }
  
  .info-item {
    display: flex;
    margin-bottom: 10rpx;
  }
  
  .info-label {
    width: 160rpx;
    font-size: 28rpx;
    color: #666;
  }
  
  .info-value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
  
  .enrollment-actions {
    display: flex;
    justify-content: flex-end;
  }
  
  .btn-action {
    margin-left: 20rpx;
    font-size: 26rpx;
    padding: 10rpx 30rpx;
    border-radius: 6rpx;
  }
  
  .btn-view {
    color: #666;
    background-color: #f8f8f8;
    border: 1px solid #ddd;
  }
  
  .btn-approve {
    color: #fff;
    background-color: #52c41a;
  }
  
  .btn-reject {
    color: #fff;
    background-color: #f56c6c;
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 30rpx;
    margin-bottom: 30rpx;
  }
  
  .btn-page {
    font-size: 28rpx;
    color: #666;
    background-color: #f8f8f8;
    border: 1px solid #ddd;
    border-radius: 6rpx;
    padding: 10rpx 30rpx;
  }
  
  .page-info {
    margin: 0 30rpx;
    font-size: 28rpx;
    color: #666;
  }
  </style>